<?php

function saveNoteFile($data_insert,$file_name,$ModuleBean)
{
    $note_['id'] = $ModuleBean->id;
    $note_['file'] = $data_insert;
    $note_['filename'] = $file_name;
    
    require_once('include/upload_file.php');
    
    $upload_file = new UploadFile('uploadfile');

    $decodedFile = $note_['file'];
    $upload_file->set_for_soap($note_['filename'], $decodedFile);

    $ext_pos = strrpos($upload_file->stored_file_name, ".");
    $upload_file->file_ext = substr($upload_file->stored_file_name, $ext_pos + 1);
    $ModuleBean->filename = $upload_file->get_stored_file_name();
    $ModuleBean->file_mime_type = $upload_file->getMimeSoap($ModuleBean->filename);
    $ModuleBean->id = $note_['id'];
    $return_id = $ModuleBean->save();
    $upload_file->final_move($ModuleBean->id);  
}

$file_name = $_GET['file'];
$file_data =  file_get_contents("php://input");
$note_id = $_GET['nid'];

if(empty($note_id))
{
  
  file_put_contents('cache/upload/'.$file_name,$file_data);
  
} else {

    $Document = ControllerFactory::getController('Documents');
    //$Document = ControllerFactory::getController('Document');
    $Document->loadBean();
    $DocumentBean = &$Document->bean;
    $DocumentBean->id = $note_id;
    saveNoteFile($file_data,$file_name,$DocumentBean);
}


echo json_encode(array("file"=>$file_name));

die;
?>